<template>
    <div>
        <el-dialog center class="global-dialog" v-model="dialogVisable" width="60%" top="10vh" :show-close="false"
            :close-on-click-modal="false" @close="close1">
            <template #title>
                <div class="my-header" v-loading="detail_loading">
                    <el-tabs v-model="tabId" class="demo-tabs">
                        <el-tab-pane label="基本信息" name="1">
                            <el-form :model="diaForm" ref="DiaForm" :rules="rules" status-icon label-width="110px" status>
                                <el-row :gutter="20">
                                    <el-col :span="12">
                                        <el-form-item label="著作名称" prop="name">
                                            <el-input placeholder="请输入" v-model="diaForm.name" style="width: 100%" maxlength="50" show-word-limit clearable />
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="ISBN名称" prop="isbnBookNo">
                                            <el-input placeholder="请输入" v-model="diaForm.isbnBookNo" style="width: 100%" maxlength="20" show-word-limit  clearable/>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row :gutter="20">
                                    <el-col :span="12">
                                        <el-form-item label="著作级别" prop="workLevelId">
                                            <el-select clearable v-model="diaForm.workLevelId" placeholder="著作级别"
                                                @change="changeWorkLevel" style="width: 100%">
                                                <el-option :label="item.itemText" :value="item.itemValue"
                                                    :key="item.itemValue" v-for="item in workLevelList" />
                                            </el-select>
                                        </el-form-item>
                                    </el-col>
                                    <!-- <el-col :span="12">
                                        <el-form-item label="编著属性" prop="workAttributeId">
                                            <el-select clearable v-model="diaForm.workAttributeId" placeholder="编著属性"
                                                @change="changeWorkAttribute" style="width: 100%">
                                                <el-option :label="item.itemText" :value="item.itemValue"
                                                    :key="item.itemValue" v-for="item in workAttributeList" />
                                            </el-select>
                                        </el-form-item>
                                    </el-col> -->


                                    <el-col :span="12">
                                        <el-form-item label="语言" prop="languageId">
                                            <el-select v-model="diaForm.languageId" placeholder="请选择" style="width: 100%"
                                                @change="changeLange">
                                                <el-option :label="item.itemText" :value="item.itemValue"
                                                    :key="item.itemValue" v-for="item in languageList" />
                                            </el-select>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row :gutter="20">
                                    <el-col :span="12">
<!--                                        <el-form-item label="所属项目" prop="projectId">-->
<!--
                                            <el-select v-model="diaForm.projectId" placeholder="请选择" style="width: 100%" filterable
                                                @change="changeProject">
                                                <el-option :label="item.projectname" :value="item.id" :key="item.id"
                                                    v-for="item in projectList" />
                                            </el-select>
-->
                                          <el-form-item label="所属项目" prop="project">
                                            <el-select v-model="diaForm.project" filterable placeholder="请选择" style="width: 80%"
                                                       @change="changeProject"  clearable disabled >
                                              <el-option :label="item.projectname" :value="item.id" :key="item.id"
                                                         v-for="item in projectList"  />

                                            </el-select>
                                            <el-button type="primary" @click="open">选择</el-button>
                                          </el-form-item>
<!--                                        </el-form-item>-->
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="年份" prop="pyear">
                                            <el-select v-model="diaForm.pyear" placeholder="请选择" style="width: 100%">
                                                <el-option :label="item.itemText" :value="item.itemValue"
                                                    :key="item.itemValue" v-for="item in yearList" />
                                            </el-select>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row :gutter="20">
                                    <el-col :span="12">
                                        <el-form-item label="业务板块" prop="techClassId">
                                            <el-select clearable v-model="diaForm.techClassId" placeholder="请选择"
                                                @change="changeTechClass" style="width: 100%">
                                                <el-option :label="item.itemText" :value="item.itemValue"
                                                    :key="item.itemValue" v-for="item in techClassList" />
                                            </el-select>

                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="维护单位" prop="maintainUnit">
                                            <popup-tree-input
                                            :data="orgAllList"
                                            :props="popupTreeProps"
                                            :prop="
                                            deptForm.parentName == null
                                            ? $t('message.org.top_menu')
                                            : diaForm.maintainUnit
                                            "
                                            :node-key="'' + deptForm.parentId"
                                            :current-change-handle="changeUnit"
                                            />
                                        </el-form-item>
                                    </el-col>
                                </el-row>

                                <el-row :gutter="20">
                                  <el-col :span="12">

                                    <el-form-item label="合同中规定的成果" prop="isContractSuccess" label-width="100">
                                      <el-select
                                          v-model="diaForm.isContractSuccess"
                                          placeholder="请选择"
                                          style="width: 100%">
                                        <el-option
                                            :label="item.text"
                                            :value="item.value"
                                            :key="item.value"
                                            v-for="item in options.isHightPayList"
                                        />
                                      </el-select>
                                    </el-form-item>
                                  </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="企业排名" prop="enterpriseRankingId">
                                            <el-select v-model="diaForm.enterpriseRankingId" placeholder="请选择"
                                                style="width: 100%" @change="changeRank">

                                                <el-option :label="item.itemText" :value="item.itemValue"
                                                    :key="item.itemValue" v-for="item in RankingList" />
                                            </el-select>
                                        </el-form-item>
                                    </el-col>


                                </el-row>


                                <!-- <el-row :gutter="20">
                                    <el-col :span="12">
                                        <el-form-item label="价格" prop="price">
                                            <el-input oninput="value=value.replace(/^0|[^0-9]/g,'')" type="number" maxlength="8" show-word-limit  placeholder="请输入" v-model.number="diaForm.price"
                                                style="width: 100%" />
                                        </el-form-item>
                                    </el-col> -->

                                    <!-- <el-col :span="12">
                                        <el-form-item label="页数" prop="pageNumber">
                                            <el-input oninput="value=value.replace(/^0|[^0-9]/g,'')" type="number" maxlength="7" show-word-limit  placeholder="请输入"  v-model="diaForm.pageNumber" style="width: 100%" />
                                        </el-form-item>
                                    </el-col> -->
                                <!-- </el-row> -->

                                <!-- <el-row :gutter="20">
                                    <el-col :span="12">
                                        <el-form-item label="字数" prop="wordCount">
                                            <el-input oninput="value=value.replace(/^0|[^0-9]/g,'')" type="number"  maxlength="9" show-word-limit  placeholder="请输入" v-model="diaForm.wordCount" style="width: 100%" />
                                        </el-form-item>
                                    </el-col>
                                </el-row> -->

                                <el-form-item label="出版社" prop="publisher">
                                    <el-input placeholder="请输入" v-model="diaForm.publisher" style="width: 100%" maxlength="50" show-word-limit  />
                                </el-form-item>

                                <!-- <el-form-item label="出版地点" prop="publicAddress">
                                    <el-input placeholder="请输入" v-model="diaForm.publicAddress" style="width: 100%" />
                                </el-form-item> -->

                                <el-form-item label="版本" prop="version">
                                    <el-input placeholder="请输入" v-model="diaForm.version" style="width: 100%"  maxlength="50" show-word-limit />
                                </el-form-item>


                                <el-form-item label="关键词" prop="keyword">
                                    <el-input v-model="diaForm.keyword" :autosize="{ minRows: 2, maxRows: 6 }"
                                        type="textarea" placeholder="请输入"  maxlength="300" show-word-limit clearable />
                                </el-form-item>

                                <el-form-item label="说明" prop="remark">
                                    <el-input v-model="diaForm.remark" :autosize="{ minRows: 2, maxRows: 6 }"
                                        type="textarea" placeholder="请输入" maxlength="300" show-word-limit clearable />
                                </el-form-item>
                            </el-form>
                        </el-tab-pane>

                         <el-tab-pane label="参编单位" name="2">
                            <UnitMembers v-if="dialogVisable" :members="unitList" :membersFlag="unitFlag" @paramsChange="changeUnitInfo" ></UnitMembers>
                        </el-tab-pane>

                       <el-tab-pane label="参编人员" name="3">
                            <PeopelMembers v-if="dialogVisable" :members="memberList" :membersFlag="memberFlag" @paramsChange="changePeopleInfo"></PeopelMembers>
                        </el-tab-pane>

                         <el-tab-pane label="相关附件" name="4">
                            <PlatformFiles v-if="dialogVisable" :files="files" @filesParams="filesParams"   download="KJSL:KJCG:XSZZ:DOWNLOAD"  upload="KJSL:KJCG:XSZZ:UPLOAD" fileDelete="KJSL:KJCG:XSZZ:FILEDELET"></PlatformFiles>
                        </el-tab-pane>
                       <el-tab-pane label="变更记录" name="5">
                            <Record v-if="id" :changeLogs="changeLogs"></Record>
                        </el-tab-pane> 
                    </el-tabs>
                </div>
            </template>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="close">关闭</el-button>
                    <el-button type="primary" @click="save">保存</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
  <!-- 项目弹窗 -->
  <el-dialog v-model="Visible" width="900px" top="17vh" :show-close="false" :close-on-click-modal="false">
    <template #title>
      <div class="my-header">
        <el-tabs v-model="activeName" class="demo-tabs">
          <el-tab-pane label="项目选择" name="first">
            <div class="search-box">
              <el-input v-model="xiangmuParams.projectName" placeholder="请输入" class="input-with-select"
                        style="width: 300px">
                <template #append>
                  <el-button type="primary" @click="open">搜索</el-button>
                </template>
              </el-input>
            </div>
            <el-table :data="options.xiangmuList" style="width: 100%" border @selection-change="handleSelectionChange1">
              <el-table-column type="selection" width="40" />
              <el-table-column prop="projectName" label="项目名称" />
              <el-table-column prop="projectNumber" label="项目编号" />
              <el-table-column prop="departmentName" label="关联部门" />
              <el-table-column prop="projectLeaderName" label="项目负责人" />
              <el-table-column prop="projectYear" label="立项年份" />
            </el-table>
            <div class="example-pagination-block">
              <el-pagination
                  background
                  layout="prev, pager, next ,total,sizes,jumper"
                  :total="options.total"
                  :page-size="xiangmuParams.size"
                  @current-change="handleCurrentChange"
                  @size-change="handleSizeChange"
              />
            </div>
          </el-tab-pane>
        </el-tabs>
        <div class="handle">
          <el-button color="#626aef" @click="Visible = false">关闭</el-button>
          <el-button type="primary" @click="toHandle1">关联</el-button>
        </div>
      </div>
    </template>
  </el-dialog>

</template>

<script>
import {
addForm,
editForm,
getDetailById,
getDictionary,
getProject
} from "@/views/science/api/academic";
import PopupTreeInput from '@/views/science/components/PopupTreeInput/index.vue';
import PlatformFiles from '@/views/science/components/platformFiles/platformFiles.vue';
import Record from '@/views/science/components/record/record.vue';
import { tips } from "@/views/science/components/tips/tips";
import { onMounted, reactive, ref, toRefs, watch } from "vue";
import PeopelMembers from "./PeopelMembers.vue";
import UnitMembers from "./UnitMembers.vue";
import {projectManagementListPage} from "@/views/science/technologyStrength/api/technologyStrength";
import Api from "@/views/science/api/profess";

export default {
    components: {
        PlatformFiles, Record,UnitMembers,PeopelMembers,PopupTreeInput
    },
    props: {

        orgAllList: {
            type: Array,
            required: true,
        },
        dialogVisable: {
            type: Boolean,
            default: false,
        },

        // falg  1:新增  2:编辑  3:详情
        flag: {
            type: String,
            default: "1",
        },
        id: {
            type: String,
            default: '',
        }
    },
    setup(props, { emit }) {
        watch(() => props.dialogVisable,
            () => {
                console.log(props.dialogVisable,'props.dialogVisable');
                // 深度监听.只有在id存在的时候调用详情的接口
                if (props.id) {
                    getDetail(props.id)
                }
            },
            { deep: true, immediate: true }
        );
        // 发送请求
        onMounted(() => {
            // 获取数据字典
            getCodeList()
            getProjectList()

        });

        let  DiaForm=ref()

        let data = reactive({
            unitFlag:false,
            memberFlag:false,
            tabId: '1',
            workLevelList: [],
            workAttributeList: [],
            techClassList: [],
            languageList: [],
            RankingList: [],
            unitNameList: [],
            detail_loading:false,

            projectList: [],//项目
            memberList: [],
            unitList: [],
            popupTreeProps: {
                label: 'name',
                children: 'children',
                value:'id',
                checkStrictly: true,
            },
            deptForm : {
                parentId: 0,
                parentName: '',
            },
            yearList: [
                { itemText: '2026年', itemValue: '2026' },
                { itemText: '2025年', itemValue: '2025' },
                { itemText: '2024年', itemValue: '2024' },
                { itemText: '2023年', itemValue: '2023' },
                { itemText: '2022年', itemValue: '2022' },
                { itemText: '2021年', itemValue: '2021' },
                { itemText: '2020年', itemValue: '2020' },
                { itemText: '2019年', itemValue: '2019' }
            ],//年份


            diaForm: {
                id: '',
                name: '',
                isbnBookNo: "",
                workLevelId: '',
                workLevel: '',
                workAttributeId: '',
                workAttribute: '',
                pyear: '',
                enterpriseRankingId: '',
                enterpriseRanking: '',
                projectId: '',
                project: '',
                techClassId: '',
                techClass: '',
                maintainUnitId: '',
                maintainUnit: '',
                // enterpriseRanking: '',
                languageId: '',
                language: '',
                price: '',
                publisher: '',
                publicAddress: '',
                pageNumber: '',
                wordCount: '',
                version: '',
            },
            files: [],
            changeLogs: [],
          isContractSuccess: '',
        });

      //清空form
      const clearForm = () =>{
        data.diaForm.isContractSuccess = ''

      }
      // 弹窗中的选择
      let options = reactive({
        xiangmuList: [], //项目列表
        projectList: [],
        contractList: [],
        total:0,
        isHightPayList:[
          {text:'否',value:'1',},
          {text:'是',value:'0',},
        ],

      })
      let Visible = ref(false)
      //项目搜索参数
      let xiangmuParams = reactive({
        projectName: '',
        projectNumber: '',
        createOrgId: '',
        level: '',
        current: 1,
        size: 10,
        projectCategory: '1',
      })
      //项目列表
      let open = async () => {
        const res = await projectManagementListPage(xiangmuParams)
        const rs = res.data.data
        options.xiangmuList = rs.records
        options.total = rs.total
        Visible.value = true
      }
      //改变页码
      const handleCurrentChange = (e) => {
        xiangmuParams.current = e
        open()
      }
      //改变页数限制
      const handleSizeChange = (e) => {
        xiangmuParams.size = e
        open()
      }
      let changeList = ref([])
      let activeName = ref('first')
      let isShow = ref(false)
      let isProject = ref(false)
      let select1 = ref([]) //项目

      let handleSelectionChange1 = (val) => {
        select1.value = val
      }
      const toHandle1 = () => {
        if (select1.value.length != 1) {
          tips('请选择一项关联', 'warning')
          return
        } else {
          let obj = select1.value[0]
          // data.diaForm.projectId = (obj as any).id
          // data.diaForm.project = (obj as any).projectName
          data.diaForm.projectId = obj.id
          data.diaForm.project = obj.projectName
          Visible.value = false
        }
      }
      Api.getProjectList().then((res) => {
        // console.log('项目列表', res.data.data)
        options.projectList = res.data.data
      })


      // 规则校验
        let rules = reactive({
            name: [
                { required: true, message: '请输入著作名称', trigger: 'blur' },
            ],
            isbnBookNo: [
                { required: true, message: '请输入ISBN书号', trigger: 'change', },
            ],
            workLevelId: [
                { required: true, message: '请选择著作级别', trigger: 'change', },
            ],
            workAttributeId: [
                { required: true, message: '请选择编著属性', trigger: 'change', },
            ],
          project: [
                { required: true, message: '请选择所属项目', trigger: 'change', },
            ],
            pyear: [
                { required: true, message: '请选择年份', trigger: 'change', },
            ],
            techClassId: [
                { required: true, message: '请选择技术分类', trigger: 'change', },
            ],
            maintainUnitId: [
                { required: true, message: '请选择维护单位', trigger: 'change' },
            ],
            maintainUnit: [
                { required: true, message: '请选择维护单位', trigger: 'change' },
            ],

            isContractSuccess: [
        { required: true, message: '请输入合同中规定的成果', trigger: 'change', },
      ],
            enterpriseRankingId: [
                { required: true, message: '请选择企业排名', trigger: 'change' },
            ],
            languageId: [
                { required: true, message: '请选择语言', trigger: 'change' },
            ],

            price: [
                { required: true, message: '请输入价格', trigger: 'change' },
            ],
            publisher: [
                { required: true, message: '请输入出版社', trigger: 'change' },
            ],
            publicAddress: [
                { required: true, message: '请输入出版地点', trigger: 'change' },
            ],
            pageNumber: [
                { required: true, message: '请输入字数', trigger: 'change' },
            ],
            version: [
                { required: true, message: '请输入版本', trigger: 'change' },
            ],
            wordCount: [
                { required: true, message: '请输入字数', trigger: 'change' },
            ],


        });


        // 修改信息

        let changeUnitInfo=(params)=>{
            data.unitFlag = false;
            data.unitList = params;
        }

        let  changePeopleInfo=(params)=>{
            data.memberFlag = false;
            data.memberList = params;
          }

        // 著作级别,编著属性,技术分类,语言,企业排名===>数据字典

        let getCodeList = () => {
            getDictionary(['KJSL_ACADEMIC_WORK_LEVEL', 'KJSL_SOFT_STATE', 'KJSL_BUSINESS_SECTOR', 'KJSL_LANGUAGE', 'KJSL_ENTERPRISE_RANKING']).then((res) => {
                data.workLevelList = res.data.data.KJSL_ACADEMIC_WORK_LEVEL;
                data.workAttributeList = res.data.data.KJSL_SOFT_STATE;
                data.techClassList = res.data.data.KJSL_BUSINESS_SECTOR;
                data.languageList = res.data.data.KJSL_LANGUAGE;
                data.RankingList = res.data.data.KJSL_ENTERPRISE_RANKING;
            });
        };


        // 项目

        let getProjectList = () => {

            getProject({}).then((res) => {

                data.projectList = res.data.data;
            });
        };


        let changeRank = (id) => {


            let itemText = data.RankingList.find(item => item.itemValue == id).itemText

            data.diaForm.enterpriseRanking = itemText
        }


        // 保存
        let save = () => {
            DiaForm.value.validate((valid) => {
                // 校验通过
                if (valid) {
                    //flag 1 新增  2 编辑  3  详情
                    if (props.flag == 1) {
                        data.diaForm.id = '';
                        addForm(
                            {
                                baseInfo: data.diaForm,
                                fileList: data.files,
                                memberList: data.memberList,
                                unitList: data.unitList,
                            }
                        ).then(() => {
                            tips("新增成功", "success");
                            DiaForm.value.resetFields();
                            emit("changeDialog", '1');
                        });
                    } else {
                        editForm(
                            {
                                baseInfo: data.diaForm,
                                fileList: data.files,
                                memberList: data.memberList,
                                unitList: data.unitList,
                            }
                        ).then(() => {
                            tips("编辑成功", "success");
                            DiaForm.value.resetFields();
                            emit("changeDialog", '1');
                        });
                    }
                }
                else {
                    return tips('请将基本信息补充完整', 'warning')
                }
            });
        }

        let filesParams = (params) => {
            data.files = params
        }

        //著作级别
        let changeWorkLevel = (id) => {
            let itemText = data.workLevelList.find(item => item.itemValue == id).itemText
            data.diaForm.workLevel = itemText
        }

        // 编著属性
        let changeWorkAttribute = (id) => {
            let itemText = data.workAttributeList.find(item => item.itemValue == id).itemText
            data.diaForm.workAttribute = itemText
            console.log('编著属性',data.diaForm.workAttribute);
        }

        // 所属项目
        let changeProject = (id) => {
            let itemText = data.projectList.find(item => item.id == id).projectname
            data.diaForm.project = itemText
        }

        // 技术分类
        let changeTechClass = (id) => {
            let itemText = data.techClassList.find(item => item.itemValue == id).itemText
            data.diaForm.techClass = itemText
        }

        //   单位
        let changeUnit = (item) => {
            data.diaForm.maintainUnitId = item.id
            data.diaForm.maintainUnit = item.name
            console.log('123',data.diaForm.workAttribute);
        }


        let changeLange = (id) => {
            let itemText = data.languageList.find(item => item.itemValue == id).itemText
            data.diaForm.language = itemText
        }


        // 通过详情查询id
        let getDetail = async (id) => {
            data.detail_loading = true
            let res = await getDetailById(id);
            data.unitFlag=true
            data.memberFlag=true
            data.diaForm = res.data.data.info
            data.unitList=res.data.data.unitList
            data.memberList=res.data.data.memberList
            data.files = res.data.data.files
            data.changeLogs = res.data.data.changeLogs
            data.detail_loading = false
        };

        // 关闭清除对话框里面的数据,附件.变更记录也要删除
        // tabId也要设置初始值,否则在电点击编辑record,新增打开会出现空白页

        let close = () => {
            data.tabId = '1';
            DiaForm.value.resetFields();
            emit("changeDialog");
        };
        let close1 = () => {
            data.unitList = []
            data.memberList = []
            data.files = []
        };

        return {
            DiaForm,
            changePeopleInfo,
            filesParams,
            changeUnitInfo,
            rules,
            changeRank,
            changeWorkLevel,
            changeWorkAttribute,
            changeProject,
            changeTechClass,
            changeUnit,
            changeLange,
            getProjectList,
            getCodeList,
            ...toRefs(data),
            close,
            save,
            close1,
          open,
          handleCurrentChange,
          handleSizeChange,
          toHandle1,
          Visible,
          handleSelectionChange1,
          changeList,
          activeName,
          isShow,
          isProject,
          xiangmuParams,
          options,
          clearForm,

        };
    },
};
</script>

<style scoped lang="scss">
.dialog-footer {
    display: flex;
    justify-content: end;
}

:deep(.el-el-dialog__header) {
    display: none;
}

// 滚动条
:deep(.demo-tabs > .el-tabs__content) {
    max-height: 500px;
    overflow-y: scroll;
    scrollbar-width: none;
    -ms-overflow-style: none;
}
</style>
